package org.servlet;

import org.domain.Account;
import org.domain.Cart;
import org.domain.Item;
import org.service.CartService;
import org.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import org.apache.log4j.Logger;

public class RemoveServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/JSP/cart/Cart.jsp";
    private static final String Error_Page = "/WEB-INF/JSP/common/Error.jsp";

    private Cart cart;
    private CartService cartService;
    private String workingItemId = "0";
    private String pre = "0";
    private Logger logger = Logger.getLogger(Class.class);
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        cartService = new CartService();
        workingItemId = request.getParameter("workingItemId");
        if(!workingItemId.equals(pre))
        {
            HttpSession session = request.getSession();
            cart = (Cart)session.getAttribute("cart");

            Item item = cart.removeItemById(workingItemId);

            if(item == null)
            {
                session.setAttribute("message","Attempted to remove null CartItem from Cart.");
                request.getRequestDispatcher(Error_Page).forward(request,response);
            }
            else {
                if(session.getAttribute("account")!=null)
                {
                    Account account = (Account)session.getAttribute("account");
                    cartService.removeItemByUserIdAndItemId(account.getUsername(),workingItemId);
                    logger.info(String.format("User (%s) Remove Item (%s).", account.getUsername(), workingItemId));
                }
                request.getRequestDispatcher(VIEW_CART).forward(request,response);
            }
            pre = workingItemId;
        }
        else
        {
            request.getRequestDispatcher(VIEW_CART).forward(request,response);
        }

    }
}
